package com.my.adminservice.user.service.Impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.my.adminservice.user.domain.dto.PasswordLoginDTO;
import com.my.adminservice.user.domain.entity.SysUser;
import com.my.adminservice.user.mapper.SysUserMapper;
import com.my.adminservice.user.service.ISysUserService;
import com.my.mycommoncore.utils.AESUtil;
import com.my.mycommoncore.utils.VerifyUtil;
import com.my.mycommondomain.domian.ResultCode;
import com.my.mycommondomain.exception.ServiceException;
import com.my.mycommonsecurity.domain.dto.LoginUserDTO;
import com.my.mycommonsecurity.domain.dto.TokenDTO;
import com.my.mycommonsecurity.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SysUserServiceImpl implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TokenService tokenService;
    @Override
    public TokenDTO login(PasswordLoginDTO loginDTO) {
        //校验手机号是否合理
        if(!VerifyUtil.checkPhone(loginDTO.getPhone())){
            throw new ServiceException("账号错误，请确认后重新登录", ResultCode.INVALID_PARA.getCode());
        }
        //检查手机号是否在数据库中
        SysUser sysUser = sysUserMapper.selectByPhoneNumber(AESUtil.encrypt(loginDTO.getPhone()));
        if(sysUser == null){
            throw new ServiceException("手机号不在数据库中");
        }
        //校验密码
        String password = AESUtil.encrypt(loginDTO.getPassword());
        if (StringUtils.isEmpty(password)) {
            throw new ServiceException("密码解析为空", ResultCode.INVALID_PARA.getCode());
        }
        String passwordEncrypt  = DigestUtil.sha256Hex(password);
        if(!passwordEncrypt.equals(sysUser.getPassword())){
            throw new ServiceException("密码不正确", ResultCode.INVALID_PARA.getCode());
        }
        // 3 校验用户状态
        if (sysUser.getStatus().equals("disable")) {
            throw new ServiceException(ResultCode.USER_DISABLE);
        }
        //设置登录信息
        LoginUserDTO loginUserDTO = new LoginUserDTO();
        loginUserDTO.setUserId(sysUser.getId());
        loginUserDTO.setUserName(sysUser.getNickName());
        loginUserDTO.setUserFrom("sys");


        return tokenService.createToken(loginUserDTO);
    }
}
